document.addEventListener('DOMContentLoaded', () => {
    // 获取所有表单和toast元素
    const forms = document.querySelectorAll('.upload-form');
    const editForms = document.querySelectorAll('.edit-form');
    const toast = document.querySelector('.toast');

    // 显示提示消息
    function showToast(message, isError = false) {
        const toastBody = toast.querySelector('.toast-body');
        toastBody.textContent = message;
        toast.classList.add('show');

        if (isError) {
            toast.classList.add('bg-danger', 'text-white');
        } else {
            toast.classList.add('bg-success', 'text-white');
        }

        setTimeout(() => {
            toast.classList.remove('show', 'bg-danger', 'bg-success', 'text-white');
        }, 3000);
    }

    // 处理图片上传表单
    forms.forEach(form => {
        const fileInput = form.querySelector('input[type="file"]');

        fileInput.addEventListener('change', async (e) => {
            e.preventDefault(); // 阻止表单默认提交
            const file = e.target.files[0];
            if (!file) return;

            // 验证文件类型和大小
            if (!file.type.startsWith('image/')) {
                showToast('请选择图片文件', true);
                fileInput.value = '';
                return;
            }

            const maxSize = 5 * 1024 * 1024; // 5MB
            if (file.size > maxSize) {
                showToast('图片大小不能超过5MB', true);
                fileInput.value = '';
                return;
            }

            // 创建 FormData 并发送请求
            const formData = new FormData(form);
            const url = form.getAttribute('action'); // 从表单的action属性获取URL

            try {
                showToast('正在上传...');
                const response = await fetch(url, {
                    method: 'POST',
                    body: formData
                });

                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }

                const result = await response.json();
                if (result.success) {
                    // 更新图片显示
                    const productCard = form.closest('.product-card');
                    const img = productCard.querySelector('.product-image');
                    const contextPath = window.location.pathname.substring(0, window.location.pathname.indexOf('/admin'));
                    
                    if (result.imageData && result.imageType) {
                        // 创建新的图片对象来预加载
                        const newImage = new Image();
                        newImage.onload = () => {
                            img.src = newImage.src;
                            showToast('图片上传成功！');
                        };
                        newImage.onerror = () => {
                            img.src = `${contextPath}/image/noproduct.png`;
                            showToast('图片加载失败，已使用默认图片', true);
                        };
                        newImage.src = `data:image/${result.imageType};base64,${result.imageData}`;
                    } else {
                        img.src = `${contextPath}/image/noproduct.png`;
                        showToast('图片上传失败，已使用默认图片', true);
                    }
                } else {
                    showToast(result.message || '上传失败', true);
                }
            } catch (error) {
                console.error('Error:', error);
                showToast('上传失败，请稍后重试', true);
            }

            // 重置文件输入框
            fileInput.value = '';
        });
    });

    // 处理商品信息编辑表单
    editForms.forEach(form => {
        form.addEventListener('submit', async (e) => {
            e.preventDefault();
            const submitBtn = form.querySelector('button[type="submit"]');
            const originalText = submitBtn.innerHTML;

            submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 保存中...';
            submitBtn.disabled = true;

            try {
                const formData = new FormData(form);
                const url = form.getAttribute('action'); // 获取表单的action URL
                console.log('Submitting to URL:', url); // 调试日志

                const response = await fetch(url, {
                    method: 'POST',
                    body: formData
                });

                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }

                const result = await response.json();
                if (result.success) {
                    showToast('保存成功！');
                    // 更新表单中的值
                    const inputs = form.querySelectorAll('input[type="text"], input[type="number"], textarea');
                    inputs.forEach(input => {
                        const newValue = formData.get(input.name);
                        if (newValue) {
                            input.value = newValue;
                        }
                    });
                } else {
                    showToast(result.message || '保存失败', true);
                }
            } catch (error) {
                console.error('Error:', error);
                showToast('保存失败，请稍后重试', true);
            } finally {
                submitBtn.innerHTML = originalText;
                submitBtn.disabled = false;
            }
        });
    });

    // 图片加载失败时显示默认图片
    document.querySelectorAll('.product-image').forEach(img => {
        img.addEventListener('error', (e) => {
            const contextPath = window.contextPath || '';
            e.target.src = `${contextPath}/image/noproduct.png`;
        });
    });

    // 添加商品相关函数
    window.showAddProductModal = function () {
        const addProductModal = document.getElementById('addProductModal');
        addProductModal.style.display = 'block';
        document.body.style.overflow = 'hidden';
    }

    window.closeAddProductModal = function () {
        const addProductModal = document.getElementById('addProductModal');
        addProductModal.style.display = 'none';
        document.body.style.overflow = '';
        const addProductForm = document.getElementById('addProductForm');
        addProductForm.reset();
    }

    // 点击模态框外部关闭
    window.addEventListener('click', (e) => {
        const addProductModal = document.getElementById('addProductModal');
        if (e.target === addProductModal) {
            closeAddProductModal();
        }
    });

    // 处理添加商品表单提交
    const addProductForm = document.getElementById('addProductForm');
    addProductForm.addEventListener('submit', async (e) => {
        e.preventDefault();

        const submitBtn = addProductForm.querySelector('button[type="submit"]');
        const originalText = submitBtn.textContent;
        submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 保存中...';
        submitBtn.disabled = true;

        try {
            const formData = new FormData(addProductForm);
            const response = await fetch(`${window.contextPath}/admin/addProductServlet`, {
                method: 'POST',
                body: formData
            });

            const result = await response.json();
            if (result.success) {
                showToast('商品添加成功！');
                setTimeout(() => {
                    location.reload();
                }, 1500);
            } else {
                showToast(result.message || '添加失败', true);
            }
        } catch (error) {
            console.error('Error:', error);
            showToast('添加失败，请稍后重试', true);
        } finally {
            submitBtn.innerHTML = originalText;
            submitBtn.disabled = false;
        }
    });

    // 处理价格输入，限制小数位数
    const priceInput = document.getElementById('productPrice');
    priceInput.addEventListener('input', (e) => {
        let value = e.target.value;
        if (value.includes('.')) {
            const parts = value.split('.');
            if (parts[1].length > 2) {
                e.target.value = `${parts[0]}.${parts[1].substring(0, 2)}`;
            }
        }
    });

    // 处理图片预览
    const productImage = document.getElementById('productImage');
    productImage.addEventListener('change', (e) => {
        const file = e.target.files[0];
        if (file) {
            const maxSize = 5 * 1024 * 1024; // 5MB
            if (file.size > maxSize) {
                showToast('图片大小不能超过5MB', true);
                e.target.value = '';
                return;
            }

            if (!file.type.startsWith('image/')) {
                showToast('请选择图片文件', true);
                e.target.value = '';
                return;
            }
        }
    });

    // 处理商品信息更新
    document.querySelectorAll('.edit-form').forEach(form => {
        form.addEventListener('submit', async (e) => {
            e.preventDefault();

            try {
                const formData = new FormData(form);
                const response = await fetch(form.action, {
                    method: 'POST',
                    body: formData
                });

                const result = await response.json();
                if (result.success) {
                    showToast('商品信息更新成功', false);
                    setTimeout(() => location.reload(), 1500);
                } else {
                    showToast(result.message || '更新失败', true);
                }
            } catch (error) {
                console.error('Error:', error);
                showToast('更新失败，请稍后重试', true);
            }
        });
    });

    // 处理图片上传
    document.querySelectorAll('.upload-form').forEach(form => {
        const fileInput = form.querySelector('input[type="file"]');
        const submitButton = form.querySelector('button[type="submit"]');

        // 当选择文件时自动提交
        fileInput.addEventListener('change', () => {
            if (fileInput.files.length > 0) {
                form.submit();
            }
        });

        form.addEventListener('submit', async (e) => {
            e.preventDefault();

            if (!fileInput.files.length) {
                showToast('请选择要上传的图片', true);
                return;
            }

            try {
                const formData = new FormData(form);
                submitButton.disabled = true;

                const response = await fetch(form.action, {
                    method: 'POST',
                    body: formData
                });

                const result = await response.json();
                if (result.success) {
                    showToast('图片上传成功', false);
                    setTimeout(() => location.reload(), 1500);
                } else {
                    showToast(result.message || '上传失败', true);
                }
            } catch (error) {
                console.error('Error:', error);
                showToast('上传失败，请稍后重试', true);
            } finally {
                submitButton.disabled = false;
            }
        });
    });
});
